﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Services;
using DWF.Studio.Share.Utils;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// 工程创建窗体
    /// </summary>
    public partial class WindowCreateProject
    {
        private IConfigService _configService = null;

        public string TargetPlatform
        {
            get;
            private set;
        }

        public string WorkflowLanguage
        {
            get;
            private set;
        }

        public string SelectedPath
        {
            get;
            private set;
        }

        public string Description
        {
            get;
            private set;
        }

        public WindowCreateProject()
        {
            InitializeComponent();
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }

        private void init()
        {
            _configService = new ConfigService();
            var sysConfig = _configService.LoadSysConfig();

            this.tbxLocation.Text = sysConfig.WorkSpace;
        }

        private void BtnDirectory_Click(object sender, RoutedEventArgs e)
        {
            var sysConfig = _configService.LoadSysConfig();

            VistaFolderBrowserDialog projectDialog = new VistaFolderBrowserDialog();
            projectDialog.SelectedPath = sysConfig.WorkSpace + System.IO.Path.DirectorySeparatorChar.ToString();
            var result = projectDialog.ShowDialog(App.Current.MainWindow);

            if (result == true)
            {
                this.tbxLocation.Text = projectDialog.SelectedPath;
            }
        }

        private void BtnCreate_Click(object sender, RoutedEventArgs e)
        {
            var isvalid = Regex.IsMatch(this.tbxName.Text, @"(?!((^(con)$)|^(con)\\..*|(^(prn)$)|^(prn)\\..*|(^(aux)$)|^(aux)\\..*|(^(nul)$)|^(nul)\\..*|(^(com)[1-9]$)|^(com)[1-9]\\..*|(^(lpt)[1-9]$)|^(lpt)[1-9]\\..*)|^\\s+|.*\\s$)(^[^\\\\\\/\\:\\<\\>\\*\\?\\\\\\""\\\\|]{1,255}$)");
            if (!isvalid || string.IsNullOrWhiteSpace(this.tbxName.Text))
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                    Image = MessageBoxImage.Warning,
                    Text = LocalizationProvider.GetLocalizedString("WinCreateProject_MsgBox_Msg_Create_NameValidate"),
                    Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                };

                WpfMessageBox.Show(this, ref msgProperties);

                return;
            }
            bool isRegex = Regex.IsMatch(this.tbxLocation.Text, "[~!@#$%^&*()=+[\\]{}''\";/?,><`|！·￥…—（）\\-、；：。，》《]");
            if (isRegex||string.IsNullOrWhiteSpace(this.tbxLocation.Text))
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                    Image = MessageBoxImage.Warning,
                    Text = LocalizationProvider.GetLocalizedString("WinCreateProject_MsgBox_Msg_Create_LocationValidate"),
                    Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                };

                WpfMessageBox.Show(this, ref msgProperties);

                return;
            }
            if (this.tbxLocation.Text.Contains("\\\\"))
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                    Image = MessageBoxImage.Warning,
                    Text = LocalizationProvider.GetLocalizedString("WinCreateProject_MsgBox_Msg_Create_LocationValidate"),
                    Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                };
                WpfMessageBox.Show(this, ref msgProperties);
                return;
            }
            var path = System.IO.Path.Combine(this.tbxLocation.Text, this.tbxName.Text);
            if (!FileHelper.CheckFolderExisting(path))
            {
                FileHelper.CreateFolder(path);

                if (rbtnX86.IsChecked == true)
                {
                    TargetPlatform = StaticResource.TargetPlatform_x86;
                }
                else if (rbtnX64.IsChecked == true)
                {
                    TargetPlatform = StaticResource.TargetPlatform_x64;
                }

                if (rbtnVb.IsChecked == true)
                {
                    WorkflowLanguage = StaticResource.WorkflowLanguage_vb;
                }
                else if (rbtnCs.IsChecked == true)
                {
                    WorkflowLanguage = StaticResource.WorkflowLanguage_cs;
                }

                SelectedPath = path;
                Description = tbxDescription.Text;
                this.DialogResult = true;
            }
            else
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                    Image = MessageBoxImage.Warning,
                    Text = LocalizationProvider.GetLocalizedString("WinCreateProject_MsgBox_Msg_Create_FolderExist"),
                    Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_FolderExist"),
                };

                MessageBoxResult dlgResult = WpfMessageBox.Show(this, ref msgProperties);
            }
        }

        private void BtnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        public void SetDefaultProjectName(string defaultName)
        {
            var sysConfig = _configService.LoadSysConfig();
            var workSpace = sysConfig.WorkSpace;
            var projectName = defaultName;

            if (!String.IsNullOrWhiteSpace(workSpace) && FileHelper.CheckFolderExisting(workSpace))
            {
                var directories = Directory.GetDirectories(workSpace);

                if (directories != null)
                {
                    var directorynames = directories.Select(item => System.IO.Path.GetFileNameWithoutExtension(item));
                    var isContinue = true;
                    int num = 0;
                    while (isContinue)
                    {
                        num++;
                        projectName = defaultName + num.ToString();
                        isContinue = directorynames.Any(item => item == projectName);
                    }
                }
            }

            this.tbxName.Text = projectName;
        }
    }
}
